package demo.intercept;


import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class UsingIntercept implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request,  HttpServletResponse response, Object o) throws Exception {
        Boolean flag = false;
        System.out.println("has intercept");
        if (request.getRequestURI().contains("setCookie")) {
            response.addCookie(new Cookie("hi","ck"));
            System.out.println("intercept-just go");
            return true;
        }
        Cookie[] cookies = request.getCookies();
        String name;
        if (cookies == null) {
            return false;
        }
        for (Cookie cookie : cookies) {
            name = cookie.getName();
            if (name.contains("hi")) {
                flag = true;
            }
        }
        if (flag) {
            System.out.println("intercept-true");
        } else {
            System.out.println("intercept-false");
        }
        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }
}
